package com.data.hijack.util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author husq
 */
public final class TextUtils {
    private TextUtils() {
        throw new RuntimeException("no");
    }

    public static List<String> split(String text, char delimiter) {
        int ascii = Integer.valueOf(delimiter);

        return split(text, ascii, false);
    }

    public static List<String> split(String text, int ascii) {
        return split(text, ascii, false);
    }

    /**
     * 
     * @param text
     * @param ascii
     * @param added
     * @return
     */
    public static List<String> split(String text, int ascii, boolean added) {
        StringBuilder stext = new StringBuilder(128);
        List<String> strList = new ArrayList<>(1024);
        int len = text.length();
        for (int i = 0; i < len; i++) {
            if (text.charAt(i) == ascii) {
                String spl = "";
                if (added) {
                    spl = (char)ascii + "";
                }
                strList.add(stext.toString() + spl);
                stext.delete(0, stext.length());
                continue;
            }
            stext.append(text.charAt(i));
        }

        if (stext.length() > 0) {
            strList.add(stext.toString());
        }

        return strList;
    }

    public static String format(Throwable e, String format, Object... hint) {
        String thr = "";
        if (null != e) {
            String lineSeparator = java.security.AccessController
                .doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
            StringBuilder stackSb = new StringBuilder();
            StackTraceElement[] stactDetail = e.getStackTrace();
            stackSb.append(e.getMessage()).append(lineSeparator);
            for (StackTraceElement elem : stactDetail) {
                stackSb.append("\tat ").append(elem).append(lineSeparator);
            }
            thr = lineSeparator + stackSb.toString();
        }

        String threadName = Thread.currentThread().getName();
        long threadId = Thread.currentThread().getId();
        thr += " (thread_name: " + threadName + "[" + threadId + "])";

        return String.format(format, hint) + thr;
    }

    public static String format(String format, Object... hint) {
        return format(null, format, hint);
    }
}
